package bl.controller;

import java.util.Iterator;

import po.UserIdentity;
import po.UserPO;

import database.factory.UserDataFactory;
import database.factory.UserDataFactoryImpl;
import database.service.UserDataService;
import exception.UserDeletedException;
import exception.UserNotExistException;
import exception.WrongPasswordException;
import bl.service.LoginBLService;

public class LoginController implements LoginBLService {

	public LoginController() {
		super();
	}

	@Override
	public int requireLogin(String username, String password,
			UserIdentity userIdentity) throws WrongPasswordException,
			UserDeletedException, UserNotExistException {
		if (username.length() == 0 || password.length() == 0
				|| userIdentity == null) {
			return 0;
		}

		UserDataFactory userDataFactory = new UserDataFactoryImpl();
		UserDataService userDataService = userDataFactory.getUserDataService();
		userDataService.load();

		Iterator<UserPO> userItr = userDataService.getIterator();
		boolean isFound = false;
		int id = 0;
		while (userItr.hasNext()) {
			UserPO user = userItr.next();
			if (user.getIdentity() != userIdentity) {
				continue;
			}

			if (!username.equals(user.getUsername())) {
				continue;
			}
			isFound = true;
			if (!password.equals(user.getPassword())) {
				throw new WrongPasswordException();
			}
			id = user.getId();
			if (id <= 0) {
				throw new UserDeletedException();
			}
		}

		if (!isFound) {
			throw new UserNotExistException();
		}

		return id;
	}

}
